package net.awpspace.mobile.management.house;

import java.util.Vector;

import javax.microedition.midlet.MIDlet;

import net.awpspace.mobile.form.BaseForm;
import net.awpspace.mobile.global.Utils;

import com.sun.lwuit.Button;
import com.sun.lwuit.Container;
import com.sun.lwuit.List;
import com.sun.lwuit.TextField;
import com.sun.lwuit.animations.CommonTransitions;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;

public class SearchDialog extends BaseForm {
	private List list;
	private Vector data;
	private TextField text;
	private Container main;

	public SearchDialog(MIDlet app, BaseForm parent) {
		super(app, parent);
		// TODO Auto-generated constructor stub
		setTitle("Search");
		setTransitionInAnimator(CommonTransitions.createSlide(
				CommonTransitions.SLIDE_HORIZONTAL, true, 1200));
		setTransitionOutAnimator(CommonTransitions.createSlide(
				CommonTransitions.SLIDE_HORIZONTAL, true, 1200));

		// data = Persistence.getInstance().getData();
		createComponent();
	}

	public void createComponent() {
		main = new Container(new BorderLayout());

		Container search = new Container(new BorderLayout());
		text = new TextField();
		Button ok = new Button("Search");
		ok.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				data = Persistence.getInstance().search(text.getText());
				if (list != null) {
					SearchDialog.this.removeComponent(list);
				}
				createList();
			}
		});
		search.addComponent(BorderLayout.CENTER, text);
		search.addComponent(BorderLayout.EAST, ok);

		main.addComponent(BorderLayout.NORTH, search);
		addComponent(main);
	}

	protected void itemStateChanged() {
		// TODO Auto-generated method stub

		int index = list.getSelectedIndex();
		new DetailsMemberViewer(app, this,
				(HouseMember) (data.elementAt(index))).show();
	}

	public void createList() {
		if (data.size() == 0) {
			Utils.getInstance().alert("Không tìm thấy dữ liệu!");
			return;
		}
		list = new List();
		// list.setFocusable(true);
		list.setSmoothScrolling(true);
		// list.setSelectedIndex(0);
		for (int i = 0; i < data.size(); i++) {
			list.addItem(((HouseMember) data.elementAt(i)).getName());
		}
		list.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				itemStateChanged();
			}
		});
		main.addComponent(BorderLayout.CENTER, list);
	}

	protected void processCommand(ActionEvent e) {
		// TODO Auto-generated method stub

	}

}
